package com.atyoung.youngmall.product.service.impl;

import com.atyoung.youngmall.product.entity.CategoryBrandRelationEntity;
import com.atyoung.youngmall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atyoung.common.utils.PageUtils;
import com.atyoung.common.utils.Query;

import com.atyoung.youngmall.product.dao.BrandDao;
import com.atyoung.youngmall.product.entity.BrandEntity;
import com.atyoung.youngmall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> qw = new QueryWrapper<>();
        if(! StringUtils.isEmpty(params.get("key"))){
            qw.and(obj -> {
                obj.likeLeft("name",params.get("key")).or().eq("first_letter",params.get("key"));
            });
        }
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), qw);

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        Long brandId = brand.getBrandId();
        String brandName = brand.getName();
        this.baseMapper.updateById(brand);
        //更新冗余字段
        if(!StringUtils.isEmpty(brandName)){
            UpdateWrapper<CategoryBrandRelationEntity> qw = new UpdateWrapper<CategoryBrandRelationEntity>();
            qw.set("brand_name",brandName);
            qw.eq("brand_id",brandId);
            categoryBrandRelationService.update(qw);
        }
    }

}